#include "grp.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>


void initGraph(graph_t *gptr, int size){
    gptr->size = size;
    gptr->mat = (struct gnode *) malloc(sizeof(struct gnode)*size);
    for (int i=0;i < size;i++) {
        gptr->mat[i].next = NULL;
        gptr->mat[i].weight = 0;
        gptr->mat[i].data = i;
    }

}

void freeGraph(graph_t *gptr) {
    struct gnode *ptr, *next;
    for (int i=0;i < gptr->size; i++) {
        ptr = gptr->mat[i].next;
        while(ptr!=NULL) {
            next = ptr->next;
            free(ptr);
            ptr = next;
        }
    }
    free(gptr->mat);
    gptr->size = 0;
}


void addEdge(graph_t *gptr, int i, int j, int weight) {
    if (i >= gptr->size || j >= gptr->size)
        return;
    struct gnode *newNode = (struct gnode *)malloc(sizeof(struct gnode));
    newNode->weight = weight;
    newNode->data = j;
    newNode->next = gptr->mat[i].next;
    gptr->mat[i].next = newNode;
}

void displayMatrix(graph_t *gptr) {
    struct gnode *ptr, *next;
    for (int i = 0; i < gptr->size; i++) {
        printf("%d -> ", i);
        ptr = gptr->mat[i].next;
        while(ptr!=NULL) {
            if (ptr->next == NULL)
                printf("%d, %d\n", ptr->data, ptr->weight);
            else
                printf("%d, %d -> ", ptr->data, ptr->weight);
            ptr = ptr->next;
        }
    }
}

